package com.example.demoexample.view.recycleview;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.demoexample.R;

import java.util.List;

public class OneAdapter extends RecyclerView.Adapter<OneAdapter.VH> {
    private List<RecycleData> list;
    public int opened = -1;

    public OneAdapter(List<RecycleData> list) {
        this.list = list;
    }

    public void setData(List<RecycleData> list) {
        this.list.clear();
        this.list.addAll(list);
        opened = -1;
        notifyDataSetChanged();
    }

    @Override
    public VH onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_one_daapter, null);
        return new VH(view);
    }

    @Override
    public void onBindViewHolder(VH holder, int position) {
        RecycleData recycleData = list.get(position);
        holder.bind(position, recycleData);
    }

    @Override
    public int getItemCount() {

        return list.size();
    }

    public class VH extends RecyclerView.ViewHolder implements View.OnClickListener {

        private final LinearLayout linTitle;
        private final TextView textView;
        private final RelativeLayout rlContent;
        private final TextView tvName;
        private final TextView tvMoney;

        public VH(View itemView) {
            super(itemView);

            linTitle = itemView.findViewById(R.id.lin_title);
            textView = itemView.findViewById(R.id.tv_title);
            rlContent = itemView.findViewById(R.id.rl_content);
            tvName = itemView.findViewById(R.id.tv_name);
            tvMoney = itemView.findViewById(R.id.tv_money);
            itemView.setOnClickListener(this);
        }

        public void bind(int pos, RecycleData data) {
            textView.setText(data.title);
            tvName.setText(data.name);
            tvMoney.setText(data.Money);
            if (pos == opened) {
                rlContent.setVisibility(View.VISIBLE);
            } else {
                rlContent.setVisibility(View.GONE);
            }
        }

        @Override
        public void onClick(View v) {
            if (opened == getPosition()) {
                opened = -1;
                notifyItemChanged(getPosition());
            } else {
                int oldOpend = opened;
                opened = getPosition();
                notifyItemChanged(oldOpend);
                notifyItemChanged(opened);
            }
        }
    }

}
